<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getList"
    :columns="columns"
    row-key="batchId"
    :row-selection="infoSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="information:management:add"
          >新增</b-button
        >
        <b-button
          icon="del"
          @click="onDelete()"
          :disabled="!rowKeys.length"
          code="information:management:remove"
          >删除</b-button
        >
      </Space>
    </template>

    <template #targetValue="{ record }">
      <span v-if="record.type == '2'">{{
        deviceIndustryEnum[record.targetValue]
      }}</span>
      <span v-else>{{
        findLabelByValue(projectList, record.targetValue)
      }}</span>
    </template>

    <template #operation="{ record }">
      <b-button
        icon="detail"
        type="link"
        @click="onView(record)"
        code="information:management:query"
        >详情</b-button
      >
      <b-button
        icon="edit"
        type="link"
        @click="onAudit(record)"
        v-if="record.isAudit != '0'"
        code="information:management:audit"
        >审核</b-button
      >
    </template>
  </ProTable>

  <FormModal :items="_items" wrapClassName="custom_modal">
    <template #customFooter="{ visible, formState }">
      <div v-if="modalType === 'disabled'">
        <b-button
          type="primary"
          @click="onPass(visible, formState)"
          v-if="!loading"
          >通过</b-button
        >
        <b-button :loading="true" type="primary" v-else></b-button>
        <b-button @click="onCancel(visible)">取消</b-button>
      </div>
      <div v-if="modalType === 'info'">
        <div v-if="formState.isAudit == '0'">
          <!-- <b-button @click="onClose(visible)">关闭</b-button> -->
        </div>
        <div v-else>
          <b-button @click="onEdit(visible)">编辑</b-button>
          <!-- <b-button @click="onCancel(visible)">取消</b-button> -->
        </div>
      </div>
      <div v-if="modalType === 'add' || modalType === 'edit'">
        <template v-if="current === 0">
          <b-button @click="onNext(visible)">下一步</b-button>
        </template>
        <template v-else>
          <b-button @click="onPre(visible)">上一步</b-button>
          <b-button type="primary" @click="onSubmit(visible)" v-if="!loading"
            >确认提交</b-button
          >
          <b-button :loading="true" type="primary" v-else></b-button>
        </template>
        <b-button @click="onCancel(visible)">取消</b-button>
      </div>
    </template>

    <template #details="{ formState }">
      <FormItemRest>
        <div v-if="modalType === 'info' || modalType === 'disabled'">
          <div class="audit_info">
            <div class="audit_title">
              <div class="audit_title_label">项目信息审核</div>
              <div
                :class="[
                  {
                    audit: formState.isAudit !== '0',
                  },
                  {
                    pass: formState.isAudit == '0',
                  },
                ]"
              >
                {{ formState.isAudit == '0' ? '已通过' : '待审核' }}
              </div>
              <div>
                <span class="audit_title_label span">任务ID: </span>
                <span> {{ proFormState.batchId || '--' }}</span>
              </div>
              <div>
                <span class="audit_title_label span">修改字段: </span>
                <span>
                  {{ proFormState.type == '1' ? '项目修改' : '行业修改' }}</span
                >
              </div>
            </div>
            <div class="audit_detail">
              <div>
                <span>创建时间: </span>
                <span> {{ proFormState.createTime || '--' }}</span>
              </div>
              <div>
                <span>申请人: </span>
                <span> {{ proFormState.createBy || '--' }}</span>
              </div>
              <div>
                <span>审核日期: </span>
                <span> {{ proFormState.auditTime || '--' }}</span>
              </div>
              <div>
                <span>审核人: </span>
                <span> {{ proFormState.auditBy || '--' }}</span>
              </div>
            </div>
          </div>
          <div class="step_content">
            <Row>
              <Col :span="6">
                <div class="content left" style="height: 100%">
                  <ProForm
                    ref="leftRef"
                    :model="proFormState"
                    :onValuesChange="_onValuesChange"
                    :items="_formItems"
                  ></ProForm>
                </div>
              </Col>
              <Col :span="18">
                <div class="content right">
                  <div class="content_info">
                    <div>
                      <span>项目总数</span>
                      <span>{{ staticMap.projectNum || '--' }}</span>
                    </div>
                    <div>
                      <span>设备总数</span>
                      <span>{{ staticMap.deviceNum || '--' }}</span>
                    </div>
                    <div v-for="item in staticMap.typeList" :key="item.typeId">
                      <span>{{ item.typeName || '--' }}</span>
                      <span>{{ item.sum || 0 }}</span>
                    </div>
                  </div>
                  <div class="right_title">设备列表</div>
                  <div class="info_table">
                    <div style="height: 0" class="info_table_view">
                      <Table
                        sticky
                        key="left"
                        :dataSource="rightData"
                        :columns="_columns"
                        :pagination="false"
                        :scroll="{ x: 'max-content', y: actualHeight - 204 }"
                      >
                        <template #bodyCell="{ column, index }">
                          <template v-if="column.dataIndex === 'index'">
                            {{
                              (infoQuery.pageNum - 1) * infoQuery.pageSize +
                              index +
                              1
                            }}
                          </template>
                        </template>
                      </Table>
                      <div class="right_pagination">
                        <Pagination
                          v-model:current="infoQuery.pageNum"
                          v-model:pageSize="infoQuery.pageSize"
                          :pageSizeOptions="[15, 30, 45]"
                          show-size-changer
                          :total="rightData.length"
                          :show-total="(total) => `共 ${total} 条`"
                        ></Pagination>
                      </div>
                    </div>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        </div>
        <template v-else>
          <div class="step_content">
            <Row>
              <Col :span="6">
                <div class="content left" style="height: 100%">
                  <ProForm
                    ref="leftRef"
                    :model="proFormState"
                    :onValuesChange="_onValuesChange"
                    :items="_formItems"
                  ></ProForm>
                </div>
              </Col>
              <Col :span="18">
                <div class="content right custom_params" v-if="current == 0">
                  <div>
                    <ProForm
                      ref="topRef"
                      :model="queryFormState"
                      :onValuesChange="onValuesChange"
                      :items="_queryItems"
                      :formColLayout="{ xs: 8, sm: 8, md: 8, lg: 8 }"
                    ></ProForm>
                  </div>
                  <div>
                    <Space :size="8">
                      <b-button @click="_getInfo">搜索</b-button>
                      <b-button @click="_onRest">重置</b-button>
                    </Space>
                  </div>
                </div>
                <div class="custom_table">
                  <div>
                    <div class="right_title">
                      {{ current == 0 ? '设备列表' : '待修改设备列表' }}
                    </div>
                    <div class="right_btn">
                      <b-button
                        v-if="current == 0"
                        @click="onJoin"
                        :disabled="!_leftList.length"
                        >加入选择</b-button
                      >
                      <b-button
                        v-else
                        @click="onRemove"
                        :disabled="!_rightList.length"
                        >移除</b-button
                      >
                      <div class="shop" v-if="current == 0">
                        <ShoppingOutlined />
                        <span class="num">{{ rightData.length }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="current == 0">
                    <div class="first_table">
                      <Table
                        v-if="current == 0"
                        key="left"
                        class="left"
                        :dataSource="filterData"
                        :columns="_columns"
                        :row-selection="_rowSelection"
                        :pagination="false"
                        row-key="deviceId"
                        :scroll="{ x: 'max-content', y: '33vh' }"
                      >
                        <template #bodyCell="{ column, index }">
                          <template v-if="column.dataIndex === 'index'">
                            {{
                              (queryFormState.pageNum - 1) *
                                queryFormState.pageSize +
                              index +
                              1
                            }}
                          </template>
                        </template>
                      </Table>
                    </div>

                    <div class="right_pagination">
                      <Pagination
                        v-model:current="queryFormState.pageNum"
                        v-model:pageSize="queryFormState.pageSize"
                        :pageSizeOptions="[15, 30, 45]"
                        @change="onShowSizeChange"
                        show-size-changer
                        :total="total"
                        :show-total="(total) => `共 ${total} 条`"
                      ></Pagination>
                    </div>
                  </div>
                  <div v-else>
                    <div class="right_table">
                      <Table
                        v-if="current !== 0"
                        sticky
                        key="right"
                        class="right"
                        :dataSource="filterRightData"
                        :columns="_columns"
                        :row-selection="rowSelection"
                        :pagination="false"
                        row-key="deviceId"
                        :scroll="{ x: 'max-content', y: actualHeight - 228 }"
                      >
                        <template #bodyCell="{ column, index }">
                          <template v-if="column.dataIndex === 'index'">
                            {{
                              (rightForm.pageNum - 1) * rightForm.pageSize +
                              index +
                              1
                            }}
                          </template>
                        </template>
                      </Table>
                    </div>
                    <div class="right_pagination">
                      <Pagination
                        v-model:current="rightForm.pageNum"
                        v-model:pageSize="rightForm.pageSize"
                        :pageSizeOptions="[15, 30, 45]"
                        show-size-changer
                        :total="rightData.length"
                        :show-total="(total) => `共 ${total} 条`"
                      ></Pagination>
                    </div>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        </template>
      </FormItemRest>
    </template>
  </FormModal>
</template>

<script lang="tsx" setup>
import { computed, nextTick, ref, watch } from 'vue';
import { hasPermission } from '@/permission';
import { ShoppingOutlined } from '@ant-design/icons-vue';
import {
  Col,
  Form,
  FormItem,
  FormItemRest,
  Input,
  Modal,
  Pagination,
  Row,
  Select,
  Space,
  Steps,
  TabPane,
  Table,
  Tabs,
  Tag,
  TreeSelect,
  message,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash-es';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { columnWidth, listToEnum, listToOption } from '@/utils/utils';
import { addDisableProperty2, treeToArray } from '@/utils/utils';
import {
  deviceBatchDelete,
  deviceBatchDetail,
  deviceBatchDeviceBatchPass,
  deviceBatchList,
  deviceBatchSave,
  getInfo,
  getProjectDeviceMapV8,
  getProjectDeviceMapV8ForDevice,
} from '@/api/device';
import { getModelInfoById } from '@/api/push';
import { deviceStore } from '../store';

let num = 0;
const proFormState = ref<Record<string, any>>({
  type: '1',
});
const queryFormState = ref<Record<string, any>>({
  pageSize: 15,
  pageNum: 1,
});

const leftData: any = ref([]);
const _leftKeys = ref<number[]>([]);
const _leftList: any = ref([]);

const _rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, all) {
    _leftList.value = all;
    _leftKeys.value = values as number[];
  },
});
const rightData: any = ref([]);
const _rightKeys = ref<number[]>([]);
const _rightList: any = ref([]);
const rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, all) {
    _rightList.value = all;
    _rightKeys.value = values as number[];
  },
});

const rowKeys: any = ref([]);
const infoSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, all) {
    rowKeys.value = values as number[];
  },
});
const modListOption = ref<Record<string, any>>([]);
watch(
  () => queryFormState.value.deviceType,
  async (val: any) => {
    console.log(val, 'val');
    if (val) {
      const res: any = await getModelInfoById({
        type: val,
        modelIds: '',
      });
      modListOption.value = listToOption(res.data, 'model', 'modelId');
    } else {
      modListOption.value = [];
    }
  },
);
const _queryItems = computed<ProFormProps['items']>(() => [
  {
    label: '项目名称',
    type: 'treeSelect',
    field: 'projectIds',
    customRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectIds}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectList.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectList.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    // props: {
    //   maxTagCount: 1,
    //   treeData: projectList.value,
    //   treeCheckable: true,
    //   fieldNames: {
    //     children: 'children',
    //     label: 'label',
    //     key: 'id',
    //     value: 'id',
    //   },
    // },
  },
  {
    label: '设备类型',
    type: 'select',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    field: 'deviceType',
    props: {
      options: deviceModeOption.value,
    },
  },
  {
    label: '行业',
    type: 'select',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    field: 'deviceIndustry',
    // hide: () => proFormState.value.type == '2',
    props: {
      options: deviceIndustryOption.value,
    },
  },
  {
    label: '设备型号',
    type: 'select',
    field: 'modelIdLists',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    props: {
      mode: 'multiple',
      maxTagCount: 1,
      options: modListOption.value.length
        ? modListOption.value
        : getModelOptions.value,
    },
  },
  // {
  //   label: '设备序列号',
  //   type: 'input',
  //   field: 'deviceCode',
  //   labelCol: { span: 8 },
  //   wrapperCol: { span: 16 },
  // },
  {
    label: '软件版本',
    type: 'input',
    field: 'version',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    customRender(state) {
      return (
        <FormItemRest>
          <Row gutter={8}>
            <Col span={12}>
              <Input
                v-model:value={state.version}
                placeholder='请输入软件版本'
              />
            </Col>
            <Col span={12}>
              <Input
                v-model:value={state.versionCode}
                placeholder='请输入编译版本'
              />
            </Col>
          </Row>
        </FormItemRest>
      );
    },
  },
  {
    label: '固件版本',
    type: 'input',
    field: 'firmwareVersion',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  },
]);

const _formItems = computed<ProFormProps['items']>(() => [
  {
    label: '修改字段',
    type: 'select',
    field: 'type',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    rules: [{ required: true, message: '请选择修改字段', trigger: 'change' }],
    props: {
      disabled: current.value === 1 || modalType.value === 'info',
      options: [
        { label: '所属项目', value: '1' },
        { label: '行业', value: '2' },
      ],
    },
  },
  {
    label: '字段修改为',
    type: 'select',
    field: 'targetValue',
    rules: [{ required: true, message: '请选择字段修改为', trigger: 'change' }],
    hide: (state) => state.type === '1',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    props: {
      disabled: current.value === 1 || modalType.value === 'info',
      options: deviceIndustryOption.value,
    },
  },
  {
    label: '字段修改为',
    type: 'treeSelect',
    field: 'targetValue',
    rules: [{ required: true, message: '请选择字段修改为', trigger: 'change' }],
    hide: (state) => state.type === '2',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    props: {
      disabled: current.value === 1 || modalType.value === 'info',
      treeData: addDisableProperty2(projectList.value),
      fieldNames: {
        children: 'children',
        label: 'label',
        key: 'id',
        value: 'id',
      },
    },
    customRender: (state) => {
      const style = {
        marginLeft: '10px',
      };
      return (
        <TreeSelect
          disabled={current.value === 1 || modalType.value === 'info'}
          v-model:value={state.targetValue}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={addDisableProperty2(projectList.value)}
          allowClear={true}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
]);

const current = ref<number>(0);

const {
  refreshStore,
  auditStatusEnum,
  auditStatusOption,
  deviceModeOption,
  deviceModeEnum,
  projectList,
  getModelEnum,
  getModelOptions,
  deviceIndustryOption,
  deviceIndustryEnum,
} = deviceStore();
const init = () => {
  refreshStore.info();
};
init();

const tableRef = ref();
const _getList = async (params: any) => {
  if (Array.isArray(params.createTime)) {
    params.createTimeStart = dayjs(params.createTime[0])
      .startOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
    params.createTimeEnd = dayjs(params.createTime[1])
      .endOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
  }
  if (Array.isArray(params.auditTime)) {
    params.auditTimeStart = dayjs(params.auditTime[0])
      .startOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
    params.auditTimeEnd = dayjs(params.auditTime[1])
      .endOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
  }
  const res: any = await deviceBatchList(params);

  return res;
};

const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  console.log(values, state, 'state', getModelOptions, '设备型号');

  queryFormState.value = {
    ...queryFormState.value,
    ...state,
  };
};
const _onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  if (state.type !== proFormState.value.type && modalType.value !== 'info')
    state.targetValue = null;
  proFormState.value = {
    ...proFormState.value,
    ...state,
  };
};

const total = ref(0);
const _getInfo = async () => {
  if (Array.isArray(queryFormState.value.projectIds)) {
    queryFormState.value.projectIds =
      queryFormState.value.projectIds?.join(',');
  }
  if (Array.isArray(queryFormState.value.modelIdLists)) {
    queryFormState.value.modelIdLists =
      queryFormState.value.modelIdLists?.join(',');
  }
  const useDeviceIds = rightData.value.map((a: any) => a.deviceId).join(',');
  const res: any = await getProjectDeviceMapV8({
    ...queryFormState.value,
    useDeviceIds,
  });
  leftData.value = res.rows;
  total.value = res.total;
};

const isDustryColumn = computed(() => {
  // if (proFormState.value.type == '1') {
  return [
    {
      title: '行业',
      dataIndex: 'deviceIndustry',
      align: 'center',
      width: columnWidth(
        'deviceIndustry',
        current.value ? rightData.value : leftData.value,
        '所属项目',
      ),
    },
  ];
  // }
  // return [];
});
const _columns = computed<ProTableProps['columns']>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    width: 100,
  },
  {
    title: '项目名称',
    dataIndex: 'shortName',
    align: 'center',
    width: columnWidth(
      'shortName',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
  },

  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    width: columnWidth(
      'deviceType',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
    customRender({ text, record }) {
      return deviceModeEnum.value[text];
    },
    // valueEnum: {
    //   ...deviceModeEnum.value,
    // },
  },
  {
    title: '设备型号',
    dataIndex: 'modelStr',
    align: 'center',
    width: columnWidth(
      'modelStr',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
  },
  ...isDustryColumn.value,
  {
    title: '设备序列号',
    align: 'center',
    dataIndex: 'deviceCode',
    width: columnWidth(
      'deviceCode',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
  },
  {
    title: '软件版本',
    align: 'center',
    dataIndex: 'softwareVersion',
    width: 100,
    customRender({ record, text }) {
      return `${record.softwareVersion || ''}${record.versionCode ? `(${record.versionCode})` : ''}`;
    },
  },
  {
    title: '固件版本',
    align: 'center',
    dataIndex: 'firmwareVersion',
    width: columnWidth(
      'firmwareVersion',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
  },
  {
    align: 'center',
    title: '地址',
    dataIndex: 'address',
    width: columnWidth(
      'address',
      current.value ? rightData.value : leftData.value,
      '所属项目',
    ),
  },
]);

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '序号',
    hideInSearch: true,
    width: 100,
    dataIndex: 'index',
    customRender({ pageSize, pageNum, index }) {
      return (pageNum.value - 1) * pageSize.value + index + 1;
    },
  },
  {
    title: '任务ID',
    dataIndex: 'batchId',
  },
  {
    title: '修改字段',
    dataIndex: 'type',
    valueEnum: {
      1: '所属项目',
      2: '行业',
    },
  },
  {
    title: '参数修改后',
    dataIndex: 'targetValue',
    hideInSearch: true,
  },
  {
    title: '修改设备数',
    dataIndex: 'num',
    hideInSearch: true,
  },

  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '审核状态',
    dataIndex: 'isAudit',
    valueEnum: {
      ...auditStatusEnum.value,
    },
    customRender({ text }) {
      const style = {
        color: text == '1' ? '#F19335' : '#26cc13',
      };
      return (
        <span style={style}>
          {auditStatusEnum.value?.[text as keyof typeof auditStatusEnum.value]}
        </span>
      );
    },
  },
  {
    title: '创建日期',
    isTime: true,
    dataIndex: 'createTime',
  },
  {
    title: '审核日期',
    dataIndex: 'auditTime',
    isTime: true,
  },
  {
    title: '审核人',
    hideInSearch: true,
    dataIndex: 'auditBy',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 220,
  },
]);

const { FormModal, open, actualHeight } = useFormModal({
  size: 'large',
  column: 1,
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const _items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);

const modalType = ref();
const onAdd = async () => {
  queryFormState.value = {
    pageSize: 15,
    pageNum: 1,
  };
  proFormState.value = {
    type: '1',
  };
  deviceIds.value = [];
  rightData.value = [];
  modalType.value = 'add';
  current.value = 0;
  _getInfo();

  open({
    title: '新增',
    modalType: 'add',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const staticMap = ref({});
// 查看
const cloneFrom = ref({});
const onView = async (record: any) => {
  const result: any = await deviceBatchDetail(record.batchId);
  proFormState.value = result.data;
  cloneFrom.value = cloneDeep(result.data);
  staticMap.value = result.data.staticMap;
  deviceIds.value = result.data.deviceIds;
  cloneDeviceIds.value = result.data.deviceIds;
  const res = await getProjectDeviceMapV8ForDevice({
    deviceIds: deviceIds.value,
  });
  rightData.value = res.data;
  if (record.isAudit != '0') _getInfo();
  modalType.value = 'info';
  current.value = 1;
  open({
    title: '详情',
    modalType: 'edit',
    defaultValue: { ...record },
    serviceApi: async (params: any): Promise<any> => {},
    hasEditPermission: hasPermission('information:management:edit'),
  });
};
// 审核
const onAudit = async (record: any) => {
  const result: any = await deviceBatchDetail(record.batchId);
  proFormState.value = result.data;
  staticMap.value = result.data.staticMap;
  deviceIds.value = result.data.deviceIds;
  modalType.value = 'disabled';
  current.value = 1;
  const res = await getProjectDeviceMapV8ForDevice({
    deviceIds: deviceIds.value,
  });
  rightData.value = res.data;
  open({
    title: '审核',
    modalType: 'disabled',
    defaultValue: { ...record },
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
// 删除
const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除当前项目？`,
    onOk: async () => {
      await deviceBatchDelete(rowKeys.value);
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};

// 通过
const onPass = async (visible: any, formState: any) => {
  loading.value = true;
  await deviceBatchDeviceBatchPass(formState.batchId);
  message.success('操作成功');
  tableRef.value.refresh();
  loading.value = false;
  visible.value = false;
};

const onCancel = async (visible: any) => {
  if (modalType.value === 'edit') {
    modalType.value = 'info';
    deviceIds.value = cloneDeviceIds.value;
    const res = await getProjectDeviceMapV8ForDevice({
      deviceIds: deviceIds.value,
    });
    rightData.value = res.data;
    // console.log(cloneFrom.value, 'cloneFrom.value');

    leftRef.value.setFieldsValue(cloneFrom.value);
    return;
  }
  visible.value = false;
};

const onEdit = async (visible: any) => {
  setTimeout(() => {
    topRef.value.resetFields();
  }, 0);
  queryFormState.value = { pageSize: 15, pageNum: 1 };
  _getInfo();
  current.value = 0;
  modalType.value = 'edit';
};
const leftRef = ref();
// 下一步
const onNext = async (visible: any) => {
  await leftRef.value.validate();
  if (!rightData.value.length)
    return message.error('请选择设备加入批量修改列表');
  current.value = 1;
};
// 上一步
const onPre = async (visible: any) => {
  current.value = 0;
};

const loading = ref(false);
// 提交
const onSubmit = async (visible: any) => {
  loading.value = true;
  if (!deviceIds.value.length) {
    loading.value = false;
    return message.error('请选择批量修改的设备!');
  }
  const params = { ...proFormState.value, deviceIds: deviceIds.value };
  await deviceBatchSave(params);
  message.success('操作成功');
  visible.value = false;
  loading.value = false;
  tableRef.value.refresh();
};

// 加入
const onJoin = () => {
  rightData.value.push(..._leftList.value);
  deviceIds.value = rightData.value.map((i: any) => i.deviceId);
  leftData.value = leftData.value.filter(
    (i: any) => !_leftKeys.value.includes(i.deviceId),
  );
  _leftList.value = [];
  _getInfo();
  message.success('已加入待修改设备列表');
};
// 移除
const onRemove = () => {
  leftData.value.push(..._rightList.value);
  rightData.value = rightData.value.filter(
    (i: any) => !_rightKeys.value.includes(i.deviceId),
  );
  _rightList.value = [];
  deviceIds.value = rightData.value.map((i: any) => i.deviceId);
  _getInfo();
};

const topRef = ref();
const _onRest = () => {
  topRef.value.resetFields();
  queryFormState.value = {
    pageSize: 15,
    pageNum: 1,
    projectIds: [],
    modelIdLists: [],
  };
  _getInfo();
};

// 列表树形回显
const findLabelByValue: any = (tree: any, id: any) => {
  for (let node of tree) {
    if (node.id == id) {
      return node.label;
    }
    if (node.children) {
      const label = findLabelByValue(node.children, id);
      if (label) {
        return label;
      }
    }
  }
  return null;
};

// 选中的设备
const deviceIds: any = ref([]);
const cloneDeviceIds: any = ref([]);
const filterData = computed(() => {
  return leftData.value.filter(
    (i: any) => !deviceIds.value.includes(i.deviceId),
  );
});

const filterRightData = computed(() => {
  const { pageNum, pageSize } = rightForm.value;
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  return rightData.value.slice(startIndex, endIndex);
});

const onShowSizeChange = (current: number, pageSize: number) => {
  _getInfo();
};

const rightForm = ref({
  pageNum: 1,
  pageSize: 15,
});

const infoQuery = ref({
  pageNum: 1,
  pageSize: 15,
});
</script>

<style lang="scss">
.step_title {
  display: flex;
  & > div {
    flex: 1;
    padding: 5px 0;
    text-align: center;
    border: 1px solid #fff;
    &:first-child {
      margin-right: 15px;
    }
    &.active {
      background: #1890ff;
      border-color: transparent;
    }
  }
}

.step_content {
  margin-top: 10px;
  .content {
    &_info {
      padding: 15px;
      display: flex;
      & > div {
        display: flex;
        flex-direction: column;
        margin-right: 80px;
      }
    }
    &.left {
      padding: 10px 8px;

      border-radius: 6px;
      background-color: rgba(0, 0, 0, 0.2);
    }
    &.right {
      &.custom_params {
        padding: 10px 8px 0;
        border-radius: 6px;
        background-color: rgba(0, 0, 0, 0.2);
        display: flex;
        & > div {
          &:first-child {
            flex: 6;
            // :deep(.ant-col) {
            //   padding: 0 8px !important;
            // }
          }
          &:last-child {
            margin-left: 10px;
            flex: 1;
          }
        }
      }
      margin-left: 8px;
      :deep(.ant-card-body) {
        padding: 0 !important;
      }
      :deep(.pro-search-form-wrap) {
        padding: 15px 5px 0 !important;
        margin-bottom: 5px;
        border-radius: 6px;
        background-color: rgba(0, 0, 0, 0.2);
      }
    }
  }
}
:deep(.ant-modal) {
  width: 1200px !important;
}

@mixin item_style {
  padding: 8px;
  margin-top: 5px;
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.2);
}

.audit_info {
  @include item_style;
  padding: 8px 0px 8px 20px;
  .audit_title {
    display: flex;
    margin-bottom: 15px;
    align-items: center;
    .audit_title_label {
      font-weight: 700;
      margin-right: 20px;
      &.span {
        margin-left: 90px;
      }
    }
    div {
      &:nth-child(2) {
        padding: 1px 10px;
        border-radius: 4px;
        &.audit {
          background-color: #f19335;
        }
        &.pass {
          background-color: #26cc13;
        }
      }
    }
  }
  .audit_detail {
    display: flex;
    & > div {
      flex: 1;
    }
  }
}
.info_table {
  :deep(.ant-table-body) {
    // min-height: 445px;
  }
}
.custom_table {
  padding: 10px;
  .right {
    :deep(.ant-table-body) {
      // min-height: 565px;
    }
  }
  :deep(.ant-table-body) {
    // min-height: 445px;
  }
  & > div {
    &:first-child {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }
  }
  .right_btn {
    display: flex;
    align-items: center;
    .shop {
      position: relative;
      font-size: 20px;
      margin-left: 20px;
      .num {
        position: absolute;
        right: -8px;
        top: 2px;
        font-size: 10px;
        background-color: #1890ff;
        border-radius: 50%;
        padding: 1px 4px;
      }
    }
  }
}

.right_title {
  position: relative;
  padding-left: 10px;
  font-weight: 700;
  &::before {
    content: '';
    display: block;
    width: 3px;
    height: 15px;
    position: absolute;
    left: 0;
    top: 50%;
    background-color: #1890ff;
    transform: translateY(-50%);
  }
}
.right_pagination {
  margin-top: 15px;
  float: right;
}

:deep(.ant-table-thead) {
  th.ant-table-cell {
    background: #0d0f0f;
  }
}
.custom_modal {
  .ant-modal .ant-modal-content .ant-modal-body {
    min-height: 70vh;
  }
}

.info_table_view {
  .ant-table {
    height: 38vh;
  }
  .ant-table-body {
    height: 33vh;
  }
}
// .first_table {
// }
.first_table,
.right_table {
  .ant-table {
    height: 38vh;
  }
  // .ant-table-body {
  //   height: calc(60vh - 200px);
  // }
}
</style>
